<template>
  <el-dialog
    v-model="packedVis"
    :title="typeList[type].title"
    :width="typeList[type].width"
    @close="clearData()"
  >
    <el-form
      v-show="type === 'packed'"
      ref="queryRef"
      :inline="true"
      :model="typeList[type].data"
      class="form-box"
    >
      <div style="display: flex; flex-wrap: wrap; justify-content: center">
        <el-col :span="20">
          <el-form-item label="订单数量：">
            <el-input
              v-model="packedForm.orderNum"
              clearable
              placeholder="请输入订单数量"
              @click="openDialog('detail')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="打包人员：">
            <el-input
              v-model="packedForm.people"
              clearable
              placeholder="请选择打包人员"
              @click="openDialog('select')"
            />
          </el-form-item>
        </el-col>
      </div>
    </el-form>

    <div v-show="type === 'tip'">请确认已打包完成，打包完后订单为出库状态</div>

    <div class="container" v-show="type === 'select'">
      <el-form
        ref="queryRef"
        :inline="true"
        :model="filterPeople"
        class="form-box"
      >
        <div style="display: flex; flex-wrap: wrap">
          <el-col :span="9">
            <el-form-item label="用户账号：">
              <el-input
                v-model="filterPeople.account"
                clearable
                placeholder="请输入用户账号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="用户名称：">
              <el-input
                v-model="filterPeople.username"
                clearable
                placeholder="请输入用户名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item>
              <el-button icon="Search" type="primary" @click="getList('select')"
                >查询</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </div>
      </el-form>
      <vxe-table
        style="margin-top: 10px"
        :data="tableData"
        height="400px"
        align="center"
        border
        :loading="loading"
        ref="selectTable"
        :row-id="'userId'"
        :checkbox-config="checkboxConfig"
      >
        <vxe-column type="radio" width="60"> </vxe-column>
        <vxe-column title="序号" type="seq" width="60"></vxe-column>
        <vxe-column field="userName" width="200" title="用户账号"></vxe-column>
        <vxe-column field="nickName" width="200" title="用户名称"></vxe-column>
        <vxe-column field="post" width="150" title="角色"></vxe-column>
        <vxe-column field="createTime" title="创建时间"></vxe-column>
      </vxe-table>
    </div>

    <div class="container" v-show="type === 'detail'">
      <el-form
        ref="queryRef"
        :inline="true"
        :model="filterDetail"
        class="form-box"
      >
        <div style="display: flex; flex-wrap: wrap">
          <el-button
            type="primary"
            style="margin-right: 12px"
            @click="deleteSelect"
            >删除所选</el-button
          >
          <el-col :span="4">
            <el-form-item>
              <el-input
                v-model="filterDetail.outNum"
                clearable
                placeholder="出库单号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item>
              <el-input
                v-model="filterDetail.code"
                clearable
                placeholder="快递单号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item>
              <el-input
                v-model="filterDetail.receiver"
                clearable
                placeholder="收货人"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item>
              <el-input
                v-model="filterDetail.phone"
                clearable
                placeholder="手机号"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item>
              <el-cascader
                style="width: 100%"
                ref="addressRef"
                v-model="filterDetail.area"
                :options="addressOptions"
                :props="cascaderProps"
                placeholder="收货省市区"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-button icon="Search" type="primary" @click="getList('detail')"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </div>
      </el-form>

      <vxe-table
        style="margin-top: 10px"
        :data="tableData"
        :height="tableHeight"
        align="center"
        border
        :loading="loading"
        ref="detailTable"
        :row-id="'outId'"
        :checkbox-config="checkboxConfig"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column title="序号" type="seq" width="60"></vxe-column>
        <vxe-column
          field="companyName"
          width="200"
          title="出库单号"
        ></vxe-column>
        <vxe-column
          field="wayBillNum"
          width="200"
          title="快递单号"
        ></vxe-column>
        <vxe-column field="outNum" width="150" title="出库数量"></vxe-column>
        <vxe-column field="breedNum" title="品种数量"></vxe-column>
        <vxe-column field="receiptByName" title="收货人"></vxe-column>
        <vxe-column field="receiptPhone" title="联系方式"></vxe-column>
        <vxe-column
          field="receiverAddress"
          width="200"
          title="收货地址"
        ></vxe-column>
        <vxe-column field="remark" title="备注"></vxe-column>
        <vxe-column field="options" title="操作">
          <template #default="{ row }">
            <el-button type="text" style="color: red">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmData()"> 确认 </el-button>
        <el-button @click="packedVis = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <PackedDialog
    v-if="['select', 'detail'].includes(childType)"
    v-model="childVis"
    :type="childType"
    :dataList="tableData"
    :outRecords="outRecords"
    :loading="selectLoading"
    isChild="132465"
    ref="dialogRef"
    @sure="sure"
  ></PackedDialog>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref } from "vue";
import {
  orderDetail,
  selectPeople,
  allocPerson,
  surePecked,
} from "@/api/scApi";
import PackedDialog from "./packedDialog.vue";

const props = defineProps({
  modelValue: { type: Boolean, required: true },
  type: { type: String },
  dataList: { type: Array, default: () => [] },
  outRecords: { type: Array, default: () => [] },
  loading: { type: Boolean, required: true },
  isChild: { type: String, required: true },
});

const emit = defineEmits(["update:modelValue", "sure", "refresh"]);
const { outRecords, isChild } = toRefs(props);

const { proxy } = getCurrentInstance();
const { out_order_status } = proxy.useDict("out_order_status");

const tableData = ref([]);
const selectTable = ref();
const detailTable = ref();
const dialogRef = ref();
const total = ref(0);
let cascaderProps = ref({
  value: "pcaId",
  label: "name",
});
let addressOptions = ref([]); //省市区数据源
let addressJSON = localStorage.getItem("addressJSON");
addressOptions.value = JSON.parse(addressJSON);

const checkboxConfig = {
  heckField: "checked",
  trigger: "row",
  reserve: true,
  range: true,
};

watch(
  () => props.dataList,
  async (val) => {
    await nextTick();
    tableData.value = val;
  },
  {
    deep: true,
    immediate: true,
  }
);

const packedVis = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

const childVis = ref(false);
const childType = ref("");
const filterPeople = ref({
  account: "",
  userName: "",
});
const packedForm = ref({
  orderNum: "",
  people: "",
});
const filterDetail = ref({
  outNum: "",
  code: "",
  receiver: "",
  phone: "",
  area: [],
});
const selectLoading = ref(false);
const selectRecords = ref([]);
const detailRecords = ref([]);

const typeList = {
  packed: {
    title: "打包分配",
    width: "500px",
  },
  tip: { title: "提示", width: "350px" },
  select: {
    title: "选择人员",
    width: "920px",
  },
  detail: {
    title: "订单详情",
    width: "1800px",
  },
};

const resetQuery = () => {
  clearData();
  getList("select");
};

function clearData() {
  filterPeople.value.username = "";
  filterPeople.value.account = "";
  filterDetail.value.outNum = "";
  filterDetail.value.code = "";
  filterDetail.value.receiver = "";
  filterDetail.value.phone = "";
  filterDetail.value.area = [];
  packedForm.value.orderNum = "";
  packedForm.value.people = "";
  tableData.value = [];
}

function getList(str) {
  const { outNum, code, receiver, phone, area } = filterDetail.value;
  const selectParams = {
    pageNum: 1,
    pageSize: 0,
    param: {
      nickName: filterPeople.value.username || undefined,
      userName: filterPeople.value.account || undefined,
    },
  };
  const orderParams = {
    outIds: outRecords.value?.map((item) => item.outId)?.join(","),
    outCode: outNum,
    wayBillNum: code,
    receiver,
    receiverPhone: phone,
    pcaProvinceId: area[0],
    pcaCityId: area[1],
    pcaAreaId: area[2],
  };
  selectLoading.value = true;
  if (str === "select") {
    selectPeople(selectParams)
      .then((res) => {
        tableData.value = res.data;
        // if (isChild.value) {
        //   selectTable.value.setRadioRow(selectRecords.value[0]);
        // }
        dialogRef.value.selectTable.setRadioRow(selectRecords.value[0]);
      })
      .finally(() => {
        selectLoading.value = false;
      });
  }

  if (str === "detail") {
    orderDetail(orderParams)
      .then((res) => {
        tableData.value = res.data;
        // if (isChild.value) {
        //   detailTable.value.setCheckboxRow(detailRecords.value, true);
        // }
        dialogRef.value.detailTable.setCheckboxRow(detailRecords.value, true);
      })
      .finally(() => {
        selectLoading.value = false;
      });
  }
}

let tableHeight = ref(0);
onMounted(() => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 360;
  });
  window.onresize = () => {
    tableHeight.value = document.body.scrollHeight - 360;
  };
});

async function openDialog(type) {
  childType.value = type;
  childVis.value = true;
  getList(type);
}

function confirmData() {
  switch (props.type) {
    case "select":
      if (selectTable.value.getCheckboxRecords().length > 1) {
        proxy.$modal.msgWarning("只能选择一条数据!");
        return;
      }
      emit("sure", {
        type: "select",
        data: selectTable.value.getRadioRecord(),
      });
      break;
    case "detail":
      emit("sure", {
        type: "detail",
        data: detailTable.value.getCheckboxRecords(),
      });
      break;
    case "packed":
      let formData = new FormData();
      formData.append(
        "outIds",
        detailRecords.value?.map((item) => item.outId).join(",")
      );
      formData.append(
        "packageAllocUser",
        selectRecords.value?.map((item) => item.userId)
      );
      allocPerson(formData).then((res) => {
        proxy.$modal.msgSuccess("分配成功");
      });
      emit("refresh");
      break;
    case "tip":
      let params = new FormData();
      params.append(
        "outIds",
        outRecords.value?.map((item) => item.outId)?.join(",")
      );
      surePecked(params).then((res) => {
        proxy.$modal.msgSuccess("已打包");
      });
      emit("refresh");
      break;
  }

  packedVis.value = false;
  clearData();
}

function sure(val) {
  selectRecords.value = val;
  if (val.type === "select") {
    selectRecords.value = [val.data];
    packedForm.value.people = val.data?.userName;
  } else if (val.type === "detail") {
    detailRecords.value = val.data;
    packedForm.value.orderNum = val.data.length;
  }
}

function deleteSelect() {
  const selectRecords = detailTable.value.getCheckboxRecords();
  detailTable.value.remove(selectRecords);
}

defineExpose({
  selectTable,
});
</script>

<style scoped>
.container {
  padding: 0 20px;
}
</style>
